﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using OT.Data;

namespace OT.Areas.Admin.Controllers
{
    public class LoginController : Controller
    {
        #region Declaration
        private OTEntitiesme db = new OTEntitiesme();
        HttpCookie myCookie = new HttpCookie("Admin");
        HttpCookie myCookie1 = new HttpCookie("AdminID");
        #endregion

        #region EncodeDecode
        public static string Base64Encode(string plainText)
        {
            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
            return System.Convert.ToBase64String(plainTextBytes);
        }

        public static string Base64Decode(string base64EncodedData)
        {
            var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
            return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }
        #endregion

        #region Index
        [HttpGet]
        public ActionResult Index()
        {
            myCookie.Expires = DateTime.Now.AddDays(-1d);
            Response.Cookies.Add(myCookie);
            myCookie1.Expires = DateTime.Now.AddDays(-1d);
            Response.Cookies.Add(myCookie1);
            return View();
        }

        [HttpPost]
        public string Index(Data.User user)
        {
            string res = "";
            if (ModelState.IsValid)
            {
                string ID=Base64Decode(user.EmailAddress);
                user = db.Users.Where(r => r.EmailAddress ==ID  && r.Password == user.Password && r.UserTypeID != 3 && r.UserTypeID != 2).FirstOrDefault();
                if (user != null)
                {
                    //HttpCookie myCookie = new HttpCookie("Admin");
                    myCookie.Value = user.FirstName;
                    myCookie.Expires = DateTime.Now.AddDays(1d);
                    Response.Cookies.Add(myCookie);

                    //HttpCookie myCookie1 = new HttpCookie("AdminID");
                    myCookie1.Value = user.UserID.ToString();
                    myCookie1.Expires = DateTime.Now.AddDays(1d);
                    Response.Cookies.Add(myCookie1);
                    res = "Admin";
                }
                else
                {
                    res = "Email or Password may be incorrect!";
                    ModelState.AddModelError("", "Email or Password is incorrect!");
                }
            }
            return res;
        }
        #endregion
    }
}
